package com.xyf.basicrtc

import android.util.Log
import org.java_websocket.WebSocket
import org.java_websocket.handshake.ClientHandshake
import org.java_websocket.server.WebSocketServer
import java.net.InetSocketAddress
import java.nio.ByteBuffer

class SocketServer constructor(port: Int) :
    WebSocketServer(InetSocketAddress(port)) {
    companion object {
        const val TAG = "SocketLive"
    }

    var webSocket: WebSocket? = null

    var onRemoteFrame: ((ByteArray) -> Unit)? = null

    override fun onOpen(conn: WebSocket?, handshake: ClientHandshake?) {
        Log.i(TAG, "onOpen")
        this.webSocket = conn
    }

    override fun onClose(conn: WebSocket?, code: Int, reason: String?, remote: Boolean) {
        Log.i(TAG, "onClose")
    }

    override fun onMessage(conn: WebSocket?, message: String?) {
        Log.i(TAG, "onMessage")
    }

    override fun onError(conn: WebSocket?, ex: java.lang.Exception?) {
        Log.i(TAG, "onError ${ex?.message}")
    }

    override fun onStart() {
        Log.i(TAG, "onStart ")
    }

    override fun onMessage(conn: WebSocket?, message: ByteBuffer?) {
        super.onMessage(conn, message)

        onRemoteFrame?.run {
            message?.let {
                Log.i(TAG, "onMessage ${message?.remaining()}")
                val buf = ByteArray(it.remaining())
                it.get(buf)
                this(buf)
            }
        }
    }

    fun sendData(h265: ByteArray) {
        webSocket?.run {
            if (isOpen) {
                send(h265)
            }
        }

    }

}


